using System;
using System.Drawing;
using System.Drawing.Printing;
using WorkOrderPrinter.Models;

namespace WorkOrderPrinter.Services
{
    public class PrintService
    {
        private readonly PrintDocument _printDocument;
        private string _printContent;

        public PrintService()
        {
            _printDocument = new PrintDocument();
            _printDocument.PrintPage += PrintDocument_PrintPage;
        }

        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            // 设置打印字体和格式
            Font font = new Font("宋体", 12);
            Brush brush = Brushes.Black;
            float yPos = 100;
            float leftMargin = e.MarginBounds.Left;
            float topMargin = e.MarginBounds.Top;
            
            // 绘制每一行文本
            string[] lines = _printContent.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
            foreach (string line in lines)
            {
                e.Graphics.DrawString(line, font, brush, leftMargin, yPos, new StringFormat());
                yPos += font.GetHeight(e.Graphics);
            }
        }

        public void PrintWorkOrder(WorkOrder workOrder, PrintTemplate template)
        {
            if (template == null || string.IsNullOrEmpty(template.Content))
                throw new ArgumentException("无效的打印模板");

            // 替换模板中的占位符
            _printContent = template.Content
                .Replace("{Model}", workOrder.Model)
                .Replace("{Batch}", workOrder.Batch)
                .Replace("{Date}", workOrder.Date.ToString("yyyy-MM-dd"))
                .Replace("{InitialSerial}", workOrder.SerialNumber.ToString())
                .Replace("{Quantity}", workOrder.Quantity.ToString())
                .Replace("{Notes}", workOrder.Notes ?? string.Empty);

            // 执行打印
            _printDocument.Print();
        }

        public void ShowPrintPreview(WorkOrder workOrder, PrintTemplate template)
        {
            if (template == null || string.IsNullOrEmpty(template.Content))
                throw new ArgumentException("无效的打印模板");

            // 替换模板中的占位符
            _printContent = template.Content
                .Replace("{Model}", workOrder.Model)
                .Replace("{Batch}", workOrder.Batch)
                .Replace("{Date}", workOrder.Date.ToString("yyyy-MM-dd"))
                .Replace("{InitialSerial}", workOrder.SerialNumber.ToString())
                .Replace("{Quantity}", workOrder.Quantity.ToString())
                .Replace("{Notes}", workOrder.Notes ?? string.Empty);

            // 显示打印预览
        
        }
    }
}
